package com.kgc.dao.impl;

import com.kgc.dao.BaseDao;
import com.kgc.dao.UserDao;
import com.kgc.entity.User;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * <h3>项目名称:demo03050</h3>
 * <p>本API描述:用户数据操作实现类</p>
 * <p>@author : AliyZhang</p>
 * <p>@date : 2021-03-08 12:49</p>
 **/
public class UserDaoImpl extends BaseDao implements UserDao {
    @Override
    public User queryUserExistsByName(String userName) {
        //sql字符串
        String sql="select * from user where userName=?";
        //参数数组
        Object[] params=new Object[1];
        params[0]=userName;
        //调用通用的查询
        ResultSet rs = executeQuery(sql, params);
        User user=null;
        try {
            while (rs.next()){
                int id = rs.getInt("id");
                String userName1 = rs.getString("userName");
                String userPwd = rs.getString("userPwd");
                user=new User(id,userName1,userPwd);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public User queryUserById(int id) {
        String sql="select * from user where id=?";
        Object[] params=new Object[1];
        params[0]=id;
        ResultSet rs = executeQuery(sql, params);
        User user=null;
        try {
            while (rs.next()){
                String userName = rs.getString("userName");
                String userPwd = rs.getString("userPwd");
                user=new User(id,userName,userPwd);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public List<User> queryUsers() {
        String sql="select * from user";
        ResultSet rs = executeQuery(sql, null);
        List<User> list=new ArrayList<>();
        try {
            while (rs.next()){
                int id=rs.getInt("id");
                String userName = rs.getString("userName");
                String userPwd = rs.getString("userPwd");
                User user=new User(id,userName,userPwd);
                list.add(user);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    /*public static void main(String[] args) {
        UserDaoImpl userDao = new UserDaoImpl();
        User user = userDao.queryUserExistsByName("admin");
        System.out.println(user+"***");
    }*/
}
